package cn.usts.edu.lesson05;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class UdpChatClient {
    public static void main(String[] args) throws Exception{
        /**
         * 准备发送端
         * DatagramSocket()
         * 构造一个数据报套接字绑定到本地主机机器上的任何可用的端口。
         */
        DatagramSocket ds = new DatagramSocket(9999);
        while (true) {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            String msg = br.readLine();
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, ip, 9998);

            // 发送数据
            ds.send(datagramPacket);
            if (msg.equals("bye")){
                break;
            }
        }
        // 关闭套接字
        ds.close();

    }
}
